package com.huadao.cart_ccs.experiment.addCell;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.huadao.cart_ccs.R;
import com.huadao.cart_ccs.base.BaseDialogFragment;
import com.huadao.cart_ccs.base.BasePresenter;
import com.huadao.cart_ccs.common.ExperimentStageManager;
import com.huadao.cart_ccs.common.ProjectManager;
import com.huadao.cart_ccs.common.TimeUtil;
import com.huadao.cart_ccs.common.dialog.DialogFragmentHelper;
import com.huadao.cart_ccs.common.dialog.IDialogResultListener;
import com.huadao.cart_ccs.experiment.liquidControl.LiquidControlDF;
import com.huadao.cart_ccs.greendao.entity.AddCell;
import com.huadao.cart_ccs.main.CartApplication;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class AddCellDF extends BaseDialogFragment implements IAddCellContract.IAddCellView {
    @BindView(R.id.sp_type)
    Spinner spType;
    @BindView(R.id.et_cellVolume)
    EditText etCellVolume;
    @BindView(R.id.et_cellAmount)
    EditText etCellAmount;
    @BindView(R.id.et_TransAct)
    EditText etTransAct;
    @BindView(R.id.et_totalVolume)
    EditText etTotalVolume;
    @BindView(R.id.switch_isMixed)
    Switch switchIsMixed;
    @BindView(R.id.tv_operate_date)
    TextView tvOperateDate;
    @BindView(R.id.tv_operate_time)
    TextView tvOperateTime;
    @BindView(R.id.tv_operate_people)
    TextView tvOperatePeople;
    @BindView(R.id.btn_startAdd)
    Button btn_startAdd;
    @BindView(R.id.btn_finishInject)
    Button btn_finishInject;
    @BindView(R.id.tv_history_record)
    TextView tv_history_record;

    private AddCellPresenter presenter;

    private Date startDate;
    private Date endDate;
    private String operator;

    private OnAddCell onAddCell;

    public interface OnAddCell{
        //开始添加
        void startAddCell(int amount,String operator,Date startDate);
        //冲刷
        void scourAfterAddCell();
    }

    @Override
    protected BasePresenter getPresenter() {
        return presenter;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialogfrag_add_cell;
    }

    @Override
    protected void onInit() {
        presenter=new AddCellPresenter(this);
        operator=CartApplication.getInstance().getOperator();
        tvOperatePeople.setText(operator);
        presenter.getAddCellHistory();
        getDialog().setCanceledOnTouchOutside(false);
    }

    @Override
    protected boolean isDialog() {
        return true;
    }

    @Override
    public void onGetAddCellHistory(List<AddCell> addCellList) {
        if (addCellList == null || addCellList.size() == 0) {
            tv_history_record.setVisibility(View.GONE);
            return;
        }
        for (AddCell injection : addCellList) {
            String text = String.format("登陆者于%tF %tT注入了总体积为%dml的细胞悬液（细胞体积%dml，细胞量%d个，TransAct %dml）", injection.getStartDate(), injection.getStartDate(), injection.getTotalVolume(), injection.getCellVolume(), injection.getCellAmount(), injection.getTransAct());
            tv_history_record.setVisibility(View.VISIBLE);
            tv_history_record.append(text);
            tv_history_record.append("\n");
        }
        initData(addCellList.get(0));
    }

    private void initData(AddCell addCell) {
        int index=0;
        String[] type=getResources().getStringArray(R.array.addCellType);
        for(int i=0;i<type.length;i++){
            if(addCell.getType().equals(type[i])){
                index=i;
                break;
            }
        }
        spType.setSelection(index);
        etCellVolume.setText(String.valueOf(addCell.getCellVolume()));
        etCellAmount.setText(String.valueOf(addCell.getCellAmount()));
        etTransAct.setText(String.valueOf(addCell.getTransAct()));
        etTotalVolume.setText(String.valueOf(addCell.getTotalVolume()));
        switchIsMixed.setChecked(addCell.getMixed());
    }

    @OnClick({R.id.btn_close, R.id.btn_startAdd,R.id.btn_finishInject})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_close:
                this.dismiss();
                break;
            case R.id.btn_startAdd:
                String err=checkParams();
                if(err!=null){
                    showToast(err);
                    return;
                }
                DialogFragmentHelper.showConfirmDialog(getActivity(), "确认添加", "请确认细胞悬液袋的卡纸是否开启！系统将开启进液泵，进行添加细胞！", new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            startDate=new Date();
                            if(onAddCell!=null){
                                int amount=Integer.parseInt(etTotalVolume.getText().toString());
                                onAddCell.startAddCell(amount,operator,startDate);
                            }
                        }
                    }
                }, true);
                break;
            case R.id.btn_finishInject:
                endDate=new Date();
                //操作时间显示结束时间
                tvOperateDate.setText(TimeUtil.date_sdf.format(endDate));
                tvOperateTime.setText(TimeUtil.time_sdf.format(endDate));
                DialogFragmentHelper.showConfirmDialog(getActivity(), "确认冲刷", "完成添加细胞进入到冲刷阶段，请确认细胞悬液袋的卡纸是否关闭！系统将开启进液泵，用培养液进行冲刷！", new IDialogResultListener<Integer>() {
                    @Override
                    public void onDataResult(Integer result) {
                        if (result == DialogInterface.BUTTON_POSITIVE) {
                            AddCellDF.this.dismiss();
                            if(onAddCell!=null){
                                AddCell addCell=generateAddCell();
                                presenter.saveAddCell(addCell);
                                onAddCell.scourAfterAddCell();
                                AddCellDF.this.dismiss();
                            }
                        }
                    }
                }, true);
                break;
        }
    }

    private AddCell generateAddCell() {
        AddCell addCell=new AddCell();
        String type= (String) spType.getSelectedItem();
        int cellVolume=Integer.parseInt(etCellVolume.getText().toString());
        int cellAmount=Integer.parseInt(etCellAmount.getText().toString());
        int transAct=Integer.parseInt(etTransAct.getText().toString());
        int totalAmount=Integer.parseInt(etTotalVolume.getText().toString());
        addCell.setType(type);
        addCell.setCellVolume(cellVolume);
        addCell.setCellAmount(cellAmount);
        addCell.setTransAct(transAct);
        addCell.setTotalVolume(totalAmount);
        addCell.setMixed(switchIsMixed.isChecked());
        addCell.setStartDate(startDate);
        addCell.setFinishDate(endDate);
        addCell.setOperator(operator);
        addCell.setProjectId(ProjectManager.getInstance().getProjectId());
        addCell.setStageId(ExperimentStageManager.getInstance().getStageId());
        return addCell;
    }

    private String checkParams() {
        String err = null;
        if (TextUtils.isEmpty(spType.getSelectedItem().toString())) {
            err = "请输入进样类型";
        }else if (TextUtils.isEmpty(etCellVolume.getText())) {
            err = "请输入体积";
        }else if (TextUtils.isEmpty(etCellAmount.getText())) {
            err = "请输入细胞量";
        }else if (TextUtils.isEmpty(etTransAct.getText())) {
            err = "请输入TransAct";
        }else if (TextUtils.isEmpty(etTotalVolume.getText())) {
            err = "请输入总体积";
        }
        return err;
    }

    public void startAddSucc(){
        btn_startAdd.setText("正在添加病毒...");
        btn_startAdd.setBackgroundResource(R.drawable.btn_info_bg);
        btn_startAdd.setEnabled(false);
    }

    public void startAddFailed(){
        btn_startAdd.setText("重新添加病毒");
        btn_startAdd.setBackgroundResource(R.drawable.shape_dialog_positive_button);
        btn_startAdd.setEnabled(true);
    }

    public void finishAddCell(){
        btn_startAdd.setVisibility(View.GONE);
        btn_finishInject.setVisibility(View.VISIBLE);
    }

    public void setOnAddCell(OnAddCell onAddCell) {
        this.onAddCell = onAddCell;
    }
}
